package cn.remex.core.util.file.upfilesave;

import cn.remex.RemexConstants;
import cn.remex.core.exception.ServiceCode;
import cn.remex.core.util.Assert;
import cn.remex.core.util.FileHelper;
import cn.remex.core.util.file.normal.FilePathHelper;
import cn.remex.core.util.imgs.ImageHelper;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;

import static cn.remex.core.util.FileHelper.convertFileSize;

/**
 * Created by guoqi on 2016/10/28.
 */
public class UploadFileSaveHelper {

    //上传的文件都来保存处理
    public static FileMeta saveFile(MultipartFile file, String pathInProject, FileRules fileRoles) {
        Assert.notNullAndEmpty(file, ServiceCode.FAIL, "上传文件不能为空！！");
        Assert.notNullAndEmpty(pathInProject, ServiceCode.FAIL, "上传文件项目中路径不能为空！！");
        //上传文件全名
        String upFileNamefull = file.getOriginalFilename();
        RemexConstants.logger.info("文件项目中路径：{} 上传文件文件名为：{}" ,pathInProject, upFileNamefull);
        Assert.isTrue(!Objects.equals(upFileNamefull.trim(), ""), ServiceCode.FAIL, "上传的文件错误");
        //上传文件类型
        String fileType = upFileNamefull.substring(upFileNamefull.lastIndexOf(".") + 1, upFileNamefull.length());
        long upFileSize = file.getSize();
        if (fileRoles != null) {
            filterFileType(file, fileType, fileRoles.getTypes());
            filterFileSize(upFileSize, fileRoles.getMaxSize(), fileRoles.getMinSize());
        }
        //路径： weeb项目路径-》
        String projectPath = FilePathHelper.getProjectPath();
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        String fileName = UUID.randomUUID()+"."+fileType;
        Path path = Paths.get(projectPath,pathInProject,fileName);
        RemexConstants.logger.info("上传文件创建文件路径：{}" , path.toString());
        FileHelper.createFilePath(path.toString());
        File localFile = new File(path.toString());
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            RemexConstants.logger.error("上传文件错误！ 文件名：{},{}" ,upFileNamefull, e);
            throw new Error("上传文件不正确错误！！，请重新上传", e);
        }
        FileMeta fileMeta = new FileMeta();
        fileMeta.setFileFullName(fileName);
        fileMeta.setSaveDate(localDateTime.toLocalDate().toString());
        fileMeta.setFilePath(pathInProject + localDateTime.toLocalDate().toString() + File.separator + fileName);
        fileMeta.setFileProjectPath(path.toString());
        fileMeta.setFileSize(upFileSize);
        fileMeta.setFileType(fileType);
        fileMeta.setFile(localFile);
        return fileMeta;
    }



    //文件类型校验
    private static boolean filterFileType(MultipartFile file, String fileType, String[] types) {
        boolean typepass = false;
        for (String type : types) {
            if( type.equals(fileType.toUpperCase())){
                typepass = true;
                break;
            }
        }
        Assert.isTrue(typepass, ServiceCode.FAIL, "上传文件类型错误！支持："+ Arrays.toString(types));
        if (fileType.toUpperCase().equals(FileTypeConst.JPG) || fileType.toUpperCase().equals(FileTypeConst.JPEG)) {
            try {
                InputStream picture = file.getInputStream();
                boolean isimage = ImageHelper.isImage(picture);
                Assert.isTrue(isimage, ServiceCode.FAIL, "上传图片错误！不是图片！");
            } catch (IOException e) {
                throw new Error("上传文件不正确，请重新上传", e);
            }
        }
        return true;
    }

    //文件大小验证
    private static boolean filterFileSize(long fileSize, int maxSize, int minSize) {
        if (minSize != 0) {
            Assert.isTrue(minSize < fileSize, ServiceCode.FAIL, "上传文件太小，必须大于："+convertFileSize(minSize));
        }
        if (maxSize != 0) {
            Assert.isTrue(maxSize > fileSize, ServiceCode.FAIL, "上传文件太大，必须小于："+convertFileSize(maxSize));
        }
        return true;
    }

}
